import { getBodymoduleCount } from "../../tools/tools/creepTool";
import structureTool from "../../tools/tools/structureTool";
import eventManager from "../event/eventManager";
import { eventMap } from "../event/eventMap"

function _mountSource() {
    Object.assign(Source.prototype, extension)
}

const extension = {
    structureType: 'source',
    taskPool: [],
    init: function (params = {}) {
        const { taskPool = [] } = params
        this.taskPool = taskPool
        this.name = this.name || `${this.pos.roomName}能源矿`
        // console.log(this.name + '完成采集，资源矿开始自检');
        this.checkSelf()
    },
    /**自检并执行任务*/
    run: function () {
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        if (!objMemory.isRuning) {
            let isRuning = false
            // 非运行中，可执行任务
            if (objMemory.publishTask.length != 0) {
                // 未发布任务，则进入自检，根据自检结果，判断是否发布任务
            }
            if (!isRuning) {
                // 无任务，则进入休眠状态，一段时间后自动唤醒
                objMemory.isRuning = true
                eventManager.add(`能源矿点${this.id}进入休眠,等待唤醒`, 10, eventMap.objToSleep, { objID: this.id })
            }
        }
    },
    /**检查自身状态，避免出现异常数据 */
    checkSelf: function () {
        structureTool.updateObjCreepList(this)
        updateSourceAllowHarvest(this)  // 判断是否允许采集
    },
    /**更新当前建筑的生命值 */
    checkSelfHits: function () {
        console.log(`当前建筑${this.name ? this.name : this.id}的生命值${this.hits ? this.hits : '*'}`);
    },
    /**更新自身状态 */
    updateSelfState: function () {
    },
    /**获取任务 */
    getTask: function () {

    },
    /**推送任务 */
    pushTask: function () {

    },
    test: function () { }
}

/**校验当前source挂载的采集者数目是否超过预期值，从而更新当前可采集状态
     * 
     * @param {Source} source 
     * @returns 
     */
function updateSourceAllowHarvest(source) {
    const count = {
        // 直接硬编码，work效率和source容量规则不变的情况下，不用动
        4000: 7,
        3000: 5,
        1500: 3
    }
    let sourceMemory = Memory.rooms[source.pos.roomName]['structure']['source'][source.id]
    if (!sourceMemory.creeps || !Array.isArray(sourceMemory.creeps) || sourceMemory.creeps.length == 0) return sourceMemory.acceptCreep = true
    if (sourceMemory.creeps.length < sourceMemory.collectPoint.length) {
        // 存在空余工位
        let workPartCount = getBodymoduleCount(sourceMemory.creeps)[WORK]
        if (workPartCount < count[source.energyCapacity]) {
            // Work部件少于恢复量                
            return sourceMemory.acceptCreep = true
        }
    }
    sourceMemory.acceptCreep = false
}


export default _mountSource